﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BakalarskaPraca.CustomComponents
{
    public partial class NumericTextBox : TextBox
    {

        public bool Decimal { get; set; }
        public bool Negative { get; set; }

        public int IntValue
        {
            get
            {
                int value;
                if (int.TryParse(this.Text, out value))
                {
                    return value;
                }
                return 0;
            }
            set { this.Text = value.ToString(CultureInfo.InvariantCulture); }
        }

        public float FloatValue
        {
            get
            {
                float value;
                if (float.TryParse(this.Text, out value))
                {
                    return value;
                }
                return 0;
            }
            set
            {
                if (!this.Decimal)
                {
                    this.Text = ((int) Math.Round(value)).ToString(CultureInfo.InvariantCulture);
                }
                else
                    this.Text = value.ToString(CultureInfo.InvariantCulture);
            }
        }

        public NumericTextBox()
        {
            this.TextAlign = HorizontalAlignment.Right;
            InitializeComponent();
        }

        public NumericTextBox(IContainer container)
        {
            this.TextAlign = HorizontalAlignment.Right;
            container.Add(this);

            InitializeComponent();
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            if (char.IsControl(key) ||
                char.IsDigit(key) ||
                (key.Equals('.') && this.Text.IndexOf('.') < 0 && this.Decimal) ||
                (key.Equals('-') && this.Text.Length == 0 && this.Negative)
                )
            {
                base.OnKeyPress(e);
            }
            else
            {
                e.Handled = true;
            }
        }
    }
}
